package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.util.TimeZoneSource;
import com.rupertjones.globalcron.web.model.DisplayableJob;
import com.rupertjones.globalcron.web.model.FormTimezone;
import org.joda.time.DateTimeZone;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
public abstract class AbstractFormAction extends AbstractAction {

    public Collection<FormTimezone> getTimezones() {
        Set<FormTimezone> all = new HashSet<FormTimezone>();
        for (DateTimeZone thisValue : TimeZoneSource.getAllTimeZones()) {
            all.add(new FormTimezone(thisValue));
        }

        List<FormTimezone> toSort = new ArrayList<FormTimezone>(all);

        Collections.sort(toSort, new Comparator<FormTimezone>() {
            @Override
            public int compare(FormTimezone o1, FormTimezone o2) {
                return o1.getId().compareTo(o2.getId());
            }
        });
        return toSort;
    }

    public Collection<FormTimezone> getCurrentlyUsedTimezones() {
        Set<FormTimezone> usedTimezones = new HashSet<FormTimezone>();
        Collection<DisplayableJob> jobs = getJobService().getAllJobs();

        for (DisplayableJob job : jobs) {
            try {
                FormTimezone tz = new FormTimezone(job.getTimezoneAsObject());
                usedTimezones.add(tz);
            } catch (IllegalArgumentException iae) {
                //ignore timezone
            }

        }
        return usedTimezones;
    }
}
